#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import os
import time
import json
from multiprocessing import Process, Lock


# 查看票
def ticket_list():
    time.sleep(1)  # 模拟网络延时
    with open("file.txt", "rt", encoding="utf-8") as read_f:
        dic = json.load(read_f)
    print("{} 当前还有{}票".format(os.getpid(), dic["count"]))


# 购买
def ticket_buy():
    # 先查看票，如有票-1， 无票提示
    time.sleep(1)  # 模拟查看延时
    with open("file.txt", "rt", encoding="utf-8") as read_f:
        dic = json.load(read_f)
    if dic["count"] > 0:
        dic["count"] -= 1
        time.sleep(1)  # 如果不添加延时，只会依赖计算能力，在一定范围内能直接处理
        with open("file.txt", "wt", encoding="utf-8") as wirte_f:
            json.dump(dic, wirte_f)
        print("{} 购票成功".format(os.getpid()))
    else:
        print("{} 无余票，购票失败".format(os.getpid()))


def task(mutex):
    ticket_list()

    mutex.acquire()
    ticket_buy()
    mutex.release()


if __name__ == '__main__':
    mutex = Lock()
    for i in range(10):
        p = Process(target=task, args=(mutex,))
        p.start()
